/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections;
using System.Diagnostics;

namespace Xceed.Silverlight.Data
{
  internal class JumpMoveAndFetchResult : MoveAndFetchResult
  {

    internal JumpMoveAndFetchResult(
      JumpMoveAndFetchAsyncResult asyncResult,
      Nullable<long> actualMove,
      ICollection fetchedItem,
      bool result,
      SourcePosition endPosition,
      RelativeOffset endPositionOffset,
      EstimateInt64 totalCount )
      : this(
          asyncResult.SourcePosition,
          asyncResult.ApproximateMove,
          asyncResult.ExpectedMoveCount,
          asyncResult.ExpectedFetchCount,
          actualMove,
          fetchedItem,
          result,
          endPosition,
          endPositionOffset,
          totalCount )
    {
    }

    internal JumpMoveAndFetchResult(
      SourcePosition sourcePosition,
      bool approximateMove,
      long expectedMoveCount,
      int expectedFetchCount,
      Nullable<long> actualMove,
      ICollection fetchedItem,
      bool result,
      SourcePosition endPosition,
      RelativeOffset endPositionOffset,
      EstimateInt64 totalCount )
      : base(
          actualMove,
          fetchedItem,
          approximateMove,
          expectedMoveCount,
          expectedFetchCount,
          result,
          endPositionOffset,
          totalCount )
    {
      this.Initialize( 
        sourcePosition, 
        approximateMove, 
        expectedMoveCount, 
        expectedFetchCount, 
        actualMove, 
        fetchedItem, 
        result, 
        endPosition,
        endPositionOffset, 
        totalCount );
    }

    protected void Initialize(
      SourcePosition sourcePosition,
      bool approximateMove,
      long expectedMoveCount,
      int expectedFetchCount,
      Nullable<long> actualMove,
      ICollection fetchedItem,
      bool result,
      SourcePosition endPosition,
      RelativeOffset endPositionOffset,
      EstimateInt64 totalCount )
    {
      JumpMoveAndFetchResult.CoerceCountInformation(
        sourcePosition,
        approximateMove,
        DataUtils.GetUnit(expectedFetchCount),
        actualMove,
        fetchedItem,
        result,
        endPosition,
        ref endPositionOffset,
        ref totalCount );


      base.Initialize( actualMove, fetchedItem, approximateMove, expectedMoveCount, expectedFetchCount, result, endPositionOffset, totalCount );

      this.SourcePosition = sourcePosition;
      this.EndPositionObject = endPosition;
    }


    #region SourcePosition Property

    internal SourcePosition SourcePosition
    {
      get;
      private set;
    }

    #endregion SourcePosition Property

    #region EndPositionObject Property

    internal SourcePosition EndPositionObject
    {
      get;
      private set;
    }

    #endregion EndPositionObject Property


    internal static void CoerceCountInformation(
      SourcePosition sourcePosition,
      bool approximateMove,
      int fetchUnit,
      Nullable<long> actualMove,
      ICollection fetchedItem,
      bool result,
      SourcePosition endPosition,
      ref RelativeOffset endPositionOffset,
      ref EstimateInt64 totalCount )
    {
      if( Math.Abs( fetchUnit ) != 1 )
        throw new ArgumentException( "fetchUnit must be equal to 1 or -1.", "fetchUnit" );

      if( !actualMove.HasValue && result )
        throw new InvalidOperationException( "actualMove cannot not be null if the operation was successful." );


      Nullable<long> realBeforeFirstOffset = null;
      Nullable<long> realAfterLastOffset = null;

      if( endPosition != null )
      {
        if( endPosition.IsBeforeFirst )
        {
          realBeforeFirstOffset = 0;
        }
        else if( endPosition.IsAfterLast )
        {
          realAfterLastOffset = 0;
        }
      }

      if( !approximateMove
        && sourcePosition != null
        && sourcePosition.IsOutOfBound
        && actualMove.HasValue )
      {
        long totalDisplacement = actualMove.Value;
        long fetchDisplacement = 0;
        if( fetchedItem != null && fetchedItem.Count > 0 )
        {
          fetchDisplacement = ( result )
            ? fetchedItem.Count - 1
            : fetchedItem.Count;

          fetchDisplacement *= fetchUnit;
        }

        long realOffset = Math.Abs( actualMove.Value + fetchDisplacement );

        if( sourcePosition.IsBeforeFirst )
        {
          Debug.Assert( endPosition == null || !endPosition.IsBeforeFirst || realOffset == 0 );
          realBeforeFirstOffset = realOffset;
        }
        else
        {
          Debug.Assert( sourcePosition.IsAfterLast );
          Debug.Assert( endPosition == null || !endPosition.IsAfterLast || realOffset == 0 );

          realAfterLastOffset = realOffset;
        }
      }

      if( realBeforeFirstOffset != null && realAfterLastOffset != null )
      {
        long realTotalCount = realBeforeFirstOffset.Value + realAfterLastOffset.Value - 1;

        if( totalCount != null && !totalCount.IsEstimate )
        {
          if( totalCount.Value != realTotalCount )
            throw new ArgumentException( "totalCount is invalid.", "totalCount" );
        }
        else
        {
          totalCount = realTotalCount;
        }
      }


      if( realBeforeFirstOffset != null || realAfterLastOffset != null )
      {
        if( endPositionOffset != null && !endPositionOffset.IsEstimate )
        {
          if( ( endPositionOffset.ReferencePosition == ReferencePoint.BeforeFirst ) && ( realBeforeFirstOffset != null ) )
          {
            if( endPositionOffset.Value != realBeforeFirstOffset.Value )
              throw new ArgumentException( "An invalid reference position was specified.", "endPositionOffset" );
          }
          else if( ( endPositionOffset.ReferencePosition == ReferencePoint.AfterLast ) && ( realAfterLastOffset != null ) )
          {
            if( endPositionOffset.Value != realAfterLastOffset.Value )
              throw new ArgumentException( "An invalid reference position was specified.", "endPositionOffset" );
          }
          else
          {
            if( totalCount != null && !totalCount.IsEstimate )
            {
              long otherRealValue = ( endPositionOffset.ReferencePosition == ReferencePoint.BeforeFirst )
                ? realAfterLastOffset.Value
                : realBeforeFirstOffset.Value;

              if( endPositionOffset.Value != ( totalCount.Value - otherRealValue + 1 ) )
                throw new InvalidOperationException( "An invalid totalCount or referencePosition was specified." );
            }
          }
        }
        else
        {
          if( realBeforeFirstOffset != null )
          {
            endPositionOffset = new RelativeOffset( realBeforeFirstOffset.Value, ReferencePoint.BeforeFirst );
          }
          else
          {
            endPositionOffset = new RelativeOffset( realAfterLastOffset.Value, ReferencePoint.AfterLast );
          }
        }
      }
    }
  }
}
